package com.tanhua.server.contoller;

import com.alibaba.fastjson.JSON;
import com.tan.model.domain.ErrorResult;
import com.tan.model.domain.User;
import com.tan.model.domain.UserInfo;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.UserInfoapi;
import com.tanhua.dubbo.api.Userapi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.service.MqMessageService;
import com.tanhua.server.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static java.lang.System.currentTimeMillis;

@RestController
@RequestMapping("/user")
public class LoginController {
    //获取登录验证码，获取请求产生，响应void
    //ResponseEntity：包裹返回值,个性化状态码
    @Autowired
    UserService userService;
    @DubboReference
    private Userapi userapi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    MqMessageService mqMessageService;
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
       String phone = (String) map.get("phone");
       userService.sendMsg(phone);
//      return ResponseEntity.status(500).body("出错了");
       return ResponseEntity.ok(null);
    }
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
     String phone = (String)   map.get("phone");
     String verificationCode = (String) map.get("verificationCode");
     System.out.println(verificationCode);
     boolean isnew=false;
     //redis获取验证码
      String redisCode = (String) redisTemplate.opsForValue().get("smsCode_"+phone);
      System.out.println(redisCode);
      if(redisCode.equals(verificationCode)){
          redisTemplate.delete("smsCode_"+phone);
          User user =    userapi.findByMobile(phone);
          String type="0101";//登录
          if(user==null){
              //如果不存在
              type="0102";//注册
              user=new User();
              user.setMobile(phone);
              user.setPassword(DigestUtils.md5Hex("123456"));
              user.setUpdated(new Date());
              user.setCreated(new Date());
              userapi.save(user);
              user.setId(userapi.findByMobile(phone).getId());
              isnew=true;
             String hxuser = "hx"+user.getId();
             String password="123456";
            Boolean createUser =  huanXinTemplate.createUser(hxuser, password);
            if(createUser){
                userapi.updateHxUser(hxuser,user.getId(),password);
            }
          }
//          try {
//              Map mapMq=new HashMap();
//              mapMq.put("userId",user.getId().toString());
//              mapMq.put("type",type);
//              mapMq.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//             String jsonString = JSON.toJSONString(mapMq);
//
//              amqpTemplate.convertAndSend("tanhua.log.exchange",
//                      "log.user",jsonString);
//
//
//
//          }catch (Exception e){
//
//
//             e.printStackTrace();
//          }
          mqMessageService.sendLogService(user.getId(),type,"user",null);












          //如果存在生成token
          Map mapjwt=new HashMap();
          mapjwt.put("id",user.getId());
          mapjwt.put("mobile",phone);
          //2.使用Jwt工具生成token
          String token = Jwts.builder()
                  .signWith(SignatureAlgorithm.HS256,"itheima")//指定加密算法
                  .setClaims(mapjwt)//设置数据
                  .setExpiration(new Date(currentTimeMillis()+500000))//设置过期时间
                  .compact();
          Map tokenMap=new HashMap();
          tokenMap.put("token",token);
          tokenMap.put("isNew",isnew);
          return ResponseEntity.ok(tokenMap);
      }else {
         return ResponseEntity.status(500).body(ErrorResult.loginError());
      }

    }

}
